/**
 * @package      JCE Advlink
 * @copyright    Copyright (C) 2008 - 2010 Ryan Demmer. All rights reserved.
 * @author		Ryan Demmer
 * @license      GNU/GPL
 * JCE is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 */

/**
 * JCEMediaBox Popup functions
 */
JCEMediaBox = {
    Popup: {

        /**
         * Addons object
         */
        addons: {},

        /**
         * Set Addons
         * @param {String} n Addon name
         * @param {Object} o Addon Object
         */
        setAddons: function(n, o) {
            if (typeof this.addons[n] == 'undefined') {
                this.addons[n] = {};
            }
            tinymce.extend(this.addons[n], o);
        },

        /**
         * Get all addons
         * @param {String} n Optional addon name
         */
        getAddons: function(n) {
            if (n) {
                return this.addons[n];
            }

            return this.addons;
        },

        /**
         * Get / Test an addon object
         * @param {Object} v
         * @param {Object} n
         */
        getAddon: function(v, n) {
            var t = this, cp = false, r, each = tinymce.each;

            var addons = this.getAddons(n);

            each(addons, function(o, s) {
                each(o, function(fn) {
                    r = fn.call(this, v);
                    if (typeof r != 'undefined') {
                        cp = r;
                    }
                });

            });

            return cp;
        }

    },

    /**
     * Utility function to trim whitespace from a string
     * @param {String} s
     */
    trim: function(s) {
        return tinymce.trim(s);
    },

    /**
     * Set proportianl dimension calculations
     * @param {String} w Width
     * @param {String} h Height
     */
    setDimensions : function(w, h) {
        $.Plugin.setDimensions(w, h, 'jcemediabox_popup_');
    }

};
WFPopups.addPopup('jcemediabox', {

    /**
     * Check if node is a JCE MediaBox popup
     * @param {Object} n Element
     */
    check: function(n) {
        return /jce(popup|_popup|lightbox)/.test(n.className);
    },

    /**
     * Get the MIME Type from a media type value
     * @param {Object} mt Media type value
     */
    getMediaType: function(n) {
        var mt;

        switch (n.type) {
            case 'image/gif':
            case 'image/jpeg':
            case 'image/png':
            case 'image/*':
            case 'image':
                mt = 'image';
                break;
            case 'iframe':
                mt = 'iframe';
                break;
            case 'director':
            case 'application/x-director':
                mt = 'application/x-director';
                break;
            case 'windowsmedia':
            case 'mplayer':
            case 'application/x-mplayer2':
                mt = 'application/x-mplayer2';
                break;
            case 'quicktime':
            case 'video/quicktime':
                mt = 'video/quicktime';
                break;
            case 'real':
            case 'realaudio':
            case 'audio/x-pn-realaudio-plugin':
                mt = 'audio/x-pn-realaudio-plugin';
                break;
            case 'divx':
            case 'video/divx':
                mt = 'video/divx';
                break;
            case 'flash':
            case 'application/x-shockwave-flash':
                mt = 'application/x-shockwave-flash';
                break;
            case 'ajax':
            case 'text/xml':
            case 'text/html':
                mt = 'text/html';
                break;
        }

        if (!mt && n.href) {
            var o = JCEMediaBox.Popup.getAddon(n.href);

            if (o && o.type) {
                mt = o.type;
            }
        }

        return mt || '';
    },

    /**
     * Clean a link of popup attributes (does not clean rel attribute)
     * @param {Object} n
     */
    remove: function(n) {
        var ed = tinyMCEPopup.editor;

        // Cleanup
        tinymce.each(['jcepopup', 'jcelightbox', 'jcebox', 'icon-left', 'icon-right', 'icon-top-left', 'icon-top-right', 'icon-bottom-left', 'icon-bottom-right', 'noicon', 'noshow', 'autopopup-single', 'autopopup-multiple'], function(c) {
            ed.dom.removeClass(n, c);
        });

    },

    /**
     * Convert parameter string to JSON object
     */
    convertData : function(s) {
        var a = [];

        tinymce.each(tinymce.explode(s, ';'), function(n, i) {
            if (n) {
                n = n.replace(/^([^\[]+)(\[|=|:)([^\]]*)(\]?)$/, function(a, b, c, d) {
                    if (d) {
                        if (!/[^0-9]/.test(d)) {
                            return '"' + b + '":' + parseInt(d);
                        }
                        return '"' + b + '":"' + d + '"';
                    }
                    return '';
                });

                if (n) {
                    a.push(n);
                }
            }
        });

        return tinymce.util.JSON.parse('{' + a.join(',') + '}');
    },

    /**
     * Get popup parameters
     * @param {Object} n Popup node
     */
    getAttributes: function(n) {
        var ed = tinyMCEPopup.editor, DOM = tinyMCEPopup.dom, data = {};

        var title = ed.dom.getAttrib(n, 'title');
        var rel = ed.dom.getAttrib(n, 'rel');

        // No icon
        var icon = /noicon/g.test(n.className);
        DOM.get('jcemediabox_popup_icon').checked = !icon;
        DOM.get('jcemediabox_popup_icon_position').disabled = icon;

        // Get position
        if (s = /icon-(top-right|top-left|bottom-right|bottom-left|left|right)/.exec(n.className)) {
            DOM.get('jcemediabox_popup_icon_position').value = s[0];
        }

        function cleanRel(s) {
            return tinymce.trim(s.replace(new RegExp('[^' + relRX + '\s?]', 'g'), ''));
        }

        var relRX = '(alternate|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark|nofollow|licence|tag|friend)';

        if (rel && /\w+\[.*\]/.test(rel)) {
            var p = [];
            // convert to object
            data = this.convertData(rel) || {};

            tinymce.each(data, function(v, k) {
                if (DOM.get('jcemediabox_popup_' + k)) {
                    DOM.get('jcemediabox_popup_' + k).value = decodeURIComponent(v);
                    // remove from object
                    delete data[k];
                } else {
                	p.push(k + '[' + decodeURIComponent(v) + ']');
                }                
            });

            DOM.get('jcemediabox_popup_params').value = p.join(';');
            // set rel value
            if (DOM.get('rel')) {
                DOM.get('rel').value = tinymce.trim(rel);
            }

            DOM.get('jcemediabox_popup_params').value = p.join(';');
        } else {
            // remove standard rel values
            group = tinymce.trim(rel.replace(new RegExp(relRX, 'g'), ''));

            DOM.get('jcemediabox_popup_group').value = group;
            // remove group and set rel value
            if (DOM.get('rel')) {
                DOM.get('rel').value = tinymce.trim(rel.replace(group, ''));
            }
        }

        // Set type
        DOM.get('jcemediabox_popup_mediatype').value = this.getMediaType(n);

        tinymce.extend(data, {
            type : ed.dom.getAttrib(n, 'type') || ''
        });

        return data;
    },

    /**
     * Set Popup Attributes
     * @param {Object} n Link Element
     */
    setAttributes: function(n, args) {
        var ed = tinyMCEPopup.editor, DOM = tinyMCEPopup.dom;

        this.remove(n);

        // Add jcepopup class
        ed.dom.addClass(n, 'jcepopup');

        var p = {};

        tinymce.each(['title', 'caption', 'group', 'width', 'height', 'params'], function(k) {
            if (el = DOM.get('jcemediabox_popup_' + k)) {
                v = el.value;
            }
            p[k] = v;
        });

        tinymce.extend(p, args);

        var params = [];

        tinymce.each(p, function(v, k) {
            if (v) {
                if (k == 'params') {
                    params.push(ed.dom.encode(v));
                } else {
                    params.push(k + '[' + v + ']');
                }
            }
        });

        params = params.join(';');

        if (rel = ed.dom.getAttrib(n, 'rel')) {
            ed.dom.setAttrib(n, 'rel', rel + ' ' + params);
        } else {
            ed.dom.setAttrib(n, 'rel', params);
        }

        // Add noicon class
        if (!DOM.get('jcemediabox_popup_icon').checked) {
            ed.dom.addClass(n, 'noicon');
        }

        // Add icon postion class
        if (!DOM.get('jcemediabox_popup_icon').checked) {
            ed.dom.addClass(n, DOM.get('jcemediabox_popup_icon_position').value);
        }
        // Set target
        ed.dom.setAttrib(n, 'target', '_blank');

        var mt = DOM.get('jcemediabox_popup_mediatype'), mv = mt.options[mt.selectedIndex].value;

        if (n.type) {
            for (i = 0; i<mt.length; i++) {
                o = mt.options[i];

                if (o.value == n.type) {
                    mv = o.value;
                }
            }
        }
        // Set media type
        ed.dom.setAttrib(n, 'type', mv);
    },

    /**
     * Set the poup icon option
     */
    setIcon : function() {
        var DOM = tinyMCEPopup.dom;
        DOM.get('jcemediabox_popup_icon_position').disabled = !DOM.get('jcemediabox_popup_icon').checked;
    },

    /**
     * Function to call when popup extension selected
     */
    onSelect: function() {
    },

    /**
     * Call function when a file is selected / clicked
     * @param {Object} args Function arguments
     */
    onSelectFile: function(args) {
        var DOM = tinyMCEPopup.dom;
        // Set popup attributes
        tinymce.each(args, function(v, k) {
            if (DOM.get('jcemediabox_popup_' + k)) {
                DOM.get('jcemediabox_popup_' + k).value = v;
            }
        });

    }
});
